package com.wlt.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wlt.pojo.Orders;
import com.wlt.pojo.SeckillGoods;
import com.wlt.result.BaseResult;
import com.wlt.service.SeckillService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

/**
 * 秒杀商品
 */
@RestController
@RequestMapping("/user/seckillGoods")
public class SeckillGoodsController
{
    @DubboReference
    private SeckillService seckillService;
    
    
    /**
     * 用户分页查询秒杀商品
     * @param page  页码
     * @param size  每页条数
     * @return      查询结果
     */
    @GetMapping("/findPage")
    public BaseResult<Page<SeckillGoods>> findPage (int page, int size) {
        Page<SeckillGoods> pageByRedis = seckillService.findPageByRedis(page, size);
        
        return BaseResult.success(pageByRedis);
    }
    
    /**
     * 用户查询秒杀商品详情
     * @param id    商品id
     * @return      查询结果
     */
    @GetMapping ("/findById")
    public BaseResult<SeckillGoods> findById (Long id) {
        // 从Redis中查询秒杀商品
        SeckillGoods seckillGoods = seckillService.findSeckillGoodsByRedis(id);
        if (seckillGoods != null) {
            return BaseResult.success(seckillGoods);
        } else {
            // 如果Redis中查找不到，再从数据库中查询秒杀商品详情
            SeckillGoods seckillGoodsByMySql = seckillService.findSeckillGoodsByMySql(id);
            
            return BaseResult.success(seckillGoodsByMySql);
        }
    }
    
    /**
     * 创建秒杀订单
     * @param orders    订单对象
     * @param userId    用户id
     * @return          创建的订单对象
     */
    @PostMapping("/add")
    public BaseResult<Orders> add (@RequestBody Orders orders, @RequestHeader Long userId) {
        orders.setUserId(userId);
        Orders order = seckillService.createOrder(orders);
        
        return BaseResult.success(order);
    }
    
    /**
     * 根据id查询秒杀订单
     * @param id    订单id
     * @return      查询结果
     */
    @GetMapping("/dinfOrder")
    public BaseResult<Orders> findOrder (String id) {
        Orders order = seckillService.findOrder(id);
        
        return BaseResult.success(order);
    }
    
    /**
     * 支付秒杀订单
     * @param id    订单id
     * @return      执行结果
     */
    @GetMapping ("/pay")
    public BaseResult pay (String id) {
        // 支付秒杀订单
        Orders pay = seckillService.pay(id);
        // 将订单数据存入数据库
        
        return BaseResult.success(pay);
    }
}
